<script setup>
import { reactive, ref } from 'vue'
import { useUserStore } from "@/stores/counter";
import { addContract, getContract, modContract, getName } from "@/api/contract"

const userStore = useUserStore();
const userMsg = userStore.userMsg;
const token = userMsg.token;
const ruleFormRef = ref();
//所有合同数据
const allContracts = reactive([])
getContract({ token }).then(res => {
    allContracts.push(...res.data.data);
})
//获取8位数日期
function getNowYMD() {
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth() >= 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`
    const date = now.getDate() >= 10 ? now.getDate() : `0${now.getDate()}`
    const timeNumber = '' + year + month + date
    return timeNumber
}
//标记
//弹窗状态标记 false 隐藏 true 显示
const flag1 = ref(false);
//1. 由 编辑 进入 弹窗，flag2 为 1, 不可修改 合同编号栏
//2. 由 添加 进入 弹窗，flag2 为 0， 合同编号栏为表单
const flag2 = ref('-1')
//弹窗 内 合同
const contractInPopup = reactive({
    contractId: '',
    contractName: '',
    id: '',
    employeeName: '',
    contractType: '',
    effectiveDate: '',
    endDate: '',
    addedDate: '',
    updatedDate: '',
    notes: ''
})
//显示弹窗 添加(可修改合同编号) 编辑(不可修改合同编号)
function showPopup1() {//添加
    flag2.value = 0//修改 合同编号栏 的状态
    reset()
    showPopup()
}
function showPopup2(id) {//编辑
    flag2.value = 1;//修改 合同编号栏 的状态
    showPopup()
    fill(id)
}
function showPopup() {//弹窗显示
    flag1.value = true;
}
function fill(id) {//填充弹窗内容
    const temp = getContractById(id);
    for (let i in contractInPopup) {
        contractInPopup[i] = temp[i];
    }
}
function closePopup() {//隐藏弹窗
    flag1.value = false;
}
// 传入 合同编号 传出 合同
function getContractById(id) {
    return allContracts.find(item => item.contractId === id)
}
// Reset contract data
function reset() {
    for (let i in contractInPopup) {
        contractInPopup[i] = '';
    }
}
// Add a contract
const submit = async (formEl) => {
    console.log(formEl);
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if(contractInPopup.employeeName ==='该员工编号不存在'){return}
            console.log("submit!");
            const temp = {}//配置对象
            for (let i in contractInPopup) {
                temp[i] = contractInPopup[i]
            }
            temp.addedDate = getNowYMD();
            temp.updatedDate = temp.addedDate;
            temp.token = token
            // temp.contractType = 0;
            console.log(temp);
            addContract(temp);
            allContracts.push(temp);
            closePopup();
        } else {
            console.log("error submit!", fields);
        }
    });
}
//根据 合同编号 修改 对应合同
function modify(id) {
    if(contractInPopup.employeeName ==='该员工编号不存在'){return}
    const contract = findContract(id);
    const index = findIndex1(contract);
    modifyMsg(index);
    closePopup();
}
function findContract(id) {// 根据 合同编号 找到 对应合同
    return allContracts.find(i => i.contractId === id)
}
function findIndex1(contract) {// 根据 合同 找到 对应索引
    return allContracts.indexOf(contract)
}
function modifyMsg(index) {// 通过 索引 修改 对应信息 修改后端数据
    const ops = {}
    contractInPopup.updatedDate = getNowYMD();
    for (let i in contractInPopup) {
        allContracts[index][i] = contractInPopup[i]
        ops[i] = contractInPopup[i]
    }
    ops.token = token
    modContract(ops)
}
const rules = reactive({
    contractId: [
        { required: true, message: "请输入合同编号", trigger: "blur" },
        { min: 2, max: 50, message: "2-10个字", trigger: "blur" },
    ],
    contractName: [
        { required: true, message: "请输入合同名称", trigger: "blur" },
        { min: 2, max: 50, message: "2-10个字", trigger: "blur" },
    ],
    id: [
        { required: true, message: "请输入员工编号", trigger: "blur" },
        { min: 2, max: 50, message: "2-10个字", trigger: "blur" },
    ],
    effectiveDate: [
        { required: true, message: "请输入生效日期", trigger: "blur" },
        {
            pattern: /^20[0-9][0-9]((0[1-9]))|((1[0-2]))(((1|2)\d)|(0[1-9])|(3[0-1]))$/,
            message: "日期格式示例：20230101",
            trigger: "blur",
        },
    ],
    endDate: [
        { required: true, message: "请输入结束日期", trigger: "blur" },
        {
            pattern: /^20[0-9][0-9]((0[1-9]))|((1[0-2]))(((1|2)\d)|(0[1-9])|(3[0-1]))$/,
            message: "日期格式示例：20230101",
            trigger: "blur",
        },
    ],
    contractType: [{ required: true, message: "请选择合同类型", trigger: "change" }],
});
//根据type值，获得type对应字符
// function _type(n) {
//     if (n == 0) return '劳务合同'
//     if (n == 1) return '保密合同'
//     if (n == 2) return '其他'
// }
async function getNameById(id) {
    const  eName = await getName({
        id,token
    });
    console.log({
        id, token
    });
    contractInPopup.employeeName=eName.data.msg
}
</script>

<template>
    <el-table :data="allContracts" border style="width: 100%">
        <el-table-column prop="contractId" label="合同编号" />
        <el-table-column prop="contractName" label="合同名称" />
        <el-table-column prop="id" label="员工编号" width="" />
        <el-table-column prop="employeeName" label="员工姓名" width="" />
        <el-table-column prop="contractType" label="合同类型" />
        <!-- <el-table-column prop="_type(contractType)" label="合同类型" /> -->
        <el-table-column prop="effectiveDate" label="生效日期" />
        <el-table-column prop="endDate" label="结束日期" />
        <el-table-column prop="addedDate" label="添加时间" />
        <el-table-column prop="updatedDate" label="更新时间" />
        <el-table-column fixed="right" label="操作" width="120" prop="contractId">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="showPopup2(scope.row.contractId)">编辑</el-button>
                <!-- 传入该行的合同id -->
            </template>
        </el-table-column>
    </el-table>
    <el-button @click="showPopup1">添加合同</el-button>
    <el-dialog v-model="flag1">
        <el-form :model="contractInPopup" label-width="120px" :rules="rules" ref="ruleFormRef">
            <div>
                <el-form-item label="合同编号" prop="contractId">
                    <el-input v-model="contractInPopup.contractId" :disabled="flag2 == 1 ? true : false" />
                </el-form-item>
                <el-form-item label="合同名称" prop="contractName">
                    <el-input v-model="contractInPopup.contractName" />
                </el-form-item>
                <el-form-item label="员工编号" width="360px" prop="id" @input="getNameById(contractInPopup.id)">
                    <el-input v-model="contractInPopup.id" />
                </el-form-item>
                <el-form-item label="员工姓名" :disabled="flag2 == 1 ? true : false">
                    <el-input v-model="contractInPopup.employeeName" :disabled="true" />
                </el-form-item>
                <el-form-item label="合同类型" prop="contractType">
                    <el-select v-model="contractInPopup.contractType" placeholder="选择合同类型">
                        <el-option label="保密合同" value="保密合同" />
                        <el-option label="劳务合同" value="'劳务合同'" />
                        <el-option label="其他" value="其他" />
                    </el-select>
                </el-form-item>
                <br>
                <el-form-item label="生效日期" prop="effectiveDate">
                    <el-input v-model="contractInPopup.effectiveDate" />
                </el-form-item>
                <el-form-item label="结束日期" prop="endDate">
                    <el-input v-model="contractInPopup.endDate" />
                </el-form-item>
                <el-form-item v-if="flag2 == '1'" label="添加日期">
                    <el-input v-model="contractInPopup.addedDate" :disabled="true" />
                </el-form-item>
                <el-form-item v-if="flag2 == '1'" label="更新日期">
                    <el-input v-model="contractInPopup.updatedDate" disabled="true" />
                </el-form-item>
            </div>
            <el-form-item label="备注">
                <el-input v-model="contractInPopup.notes" type="textarea" />
            </el-form-item>
            <el-form-item>
                <el-button v-if="flag2 == '1'" type="primary" @click="modify(contractInPopup.contractId)">保存</el-button>
                <el-button v-if="flag2 == '0'" type="primary" @click="submit(ruleFormRef)">添加</el-button>
                <el-button @click="closePopup">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<style>
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-form>div {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
}

.el-form>div .el-input {
    width: 100%;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>